/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.imgs;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.LineMetrics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * <p>Project: javaseapp - Img3
 * <p>Powered by webrx On 2021-08-13 09:05:50
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */
public class Img3 {
    public static void main(String[] args) {
        int w = 800, h = 500, t = 2;
        var i = new BufferedImage(w, h, t);
        var g = i.createGraphics();
        //设置图像中文本，线程的平滑
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);

        //设置随机的背景颜色
        g.setColor(getRandColor());
        g.fillRect(0, 0, w, h);

        //画布写字
        Font font = new Font("微软雅黑", Font.BOLD, 30);
        try {
            font = Font.createFont(Font.TRUETYPE_FONT, new File("font/zh210gfsnt.ttf"));
        } catch (FontFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        font = font.deriveFont(Font.BOLD, 130f);
        g.setFont(font);
        Color c = getRandColor();
        g.setColor(new Color(0, 0, 0, 150));
        String text = "喜报";
        FontMetrics fm = g.getFontMetrics();
        int tw = fm.stringWidth(text);
        int th = fm.getHeight();
        LineMetrics line = fm.getLineMetrics(text, g);

        float ascent = line.getAscent();
        float descent = line.getDescent();


        float x = 0.0f;
        float y = ascent - descent / 2;

        x = w - tw;
        y = h - descent / 2;

        x = (w - tw) / 2;
        y = (h - th) / 2 + ascent;
        g.drawString(text, x, y);


        g.dispose();
        try {
            ImageIO.write(i, "png", new File("t.png"));
            Runtime run = Runtime.getRuntime();
            run.exec("cmd /k start t.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Color getRandColor() {
        Random rand = new Random();
        Color c = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
        return c;
    }
}
